use super::*;

pub fn relacement_column(data: String, column: &str, replace: &str)
    -> Result<String, Error> {
    let mut lines = data.lines();
    let headers = match lines.next() {
        Some(s) => s,
        None => Err("source csv file headers missing")?
    };
    let columns: Vec<&str> = headers.split(',').collect();
    let column_number = match columns.iter().position(|&e| e == column) {
        Some(n) => n,
        None => Err("not found column")?
    };
    let mut result = String::with_capacity(data.capacity());
    result.push_str(headers);
    result.push('\n');
    for l in lines {
        let mut records: Vec<&str> = l.split(',').collect();
        records[column_number] = replace;
        result.push_str(&records.join(","));
        result.push('\n');
    }
    Ok(result)
}

#[test]
fn test_replacement_column() {
    // test replace field: First Name -> Liu
    let data = String::from("First Name,Last Name,Age,City,Eyes color,Species
John,Doe,32,Tokyo,Blue,Human
Flip,Helm,12,Canberra,Red,Unknown
Terdos,Bendarian,165,Cracow,Blue,Magic tree
Dominik,Elpos,33,Paris,Purple,Orc
Brad,Doe,42,Dublin,Blue,Human
");

    let left = String::from("First Name,Last Name,Age,City,Eyes color,Species
Liu,Doe,32,Tokyo,Blue,Human
Liu,Helm,12,Canberra,Red,Unknown
Liu,Bendarian,165,Cracow,Blue,Magic tree
Liu,Elpos,33,Paris,Purple,Orc
Liu,Doe,42,Dublin,Blue,Human
");
    assert_eq!(left, relacement_column(data, "First Name", "Liu").unwrap());

    // test no csv headers
    let data = String::from("John,Doe,32,Tokyo,Blue,Human
Flip,Helm,12,Canberra,Red,Unknown
Terdos,Bendarian,165,Cracow,Blue,Magic tree
Dominik,Elpos,33,Paris,Purple,Orc
Brad,Doe,42,Dublin,Blue,Human");
    match relacement_column(data, "First Name", "Liu") {
        Ok(_) => {
            println!("test no csv headers, Failure");
            panic!();
        },
        Err(_) => {
            println!("test no csv headers, Succeed");
        }
    };

    // test not found column name
    let data = String::from("First Name,Last Name,Age,City,Eyes color,Species
John,Doe,32,Tokyo,Blue,Human
Flip,Helm,12,Canberra,Red,Unknown
Terdos,Bendarian,165,Cracow,Blue,Magic tree
Dominik,Elpos,33,Paris,Purple,Orc
Brad,Doe,42,Dublin,Blue,Human");
    match relacement_column(data, "AABB", "Liu") {
        Ok(_) => {
            println!("test not found column name, Failure");
            panic!();
        },
        Err(_) => {
            println!("test not found column name, Succeed");
        }
    };
}